layui.use('table', function () {
    let table = layui.table,
        form = layui.form,
        $ = layui.jquery;
    //方法级渲染
    table.render({
        elem: '#deploy'
        , url: '/deploy/list?type=1'
        , toolbar: '#toolbarTable'
        , title: '自动部署配置'
        , totalRow: true
        , id: "deploy"
        ,skin: 'line'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'projectName', title: '项目名称', width: 200, sort: true}
            , {field: 'moduleName', title: '模块名称', width: 200, sort: true}
            , {field: 'namespaceName', title: '命名空间', width: 120, sort: true}
            // , {field: 'ip', title: '宿主机ip', width: 140, sort: true}
            , {field: 'localFile', title: '本地位置', width: 350, sort: true}
            , {field: 'commandStart', title: '部署命令', width: 400, sort: true}
            , {field: 'lastDeployDate', title: '最近部署时间', width: 160, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 200}
        ]]
        , even: true
        , page: true //是否显示分页
        , skip: true //开启跳页
        , limits: [15, 30, 60]
        , width: 1700
        , height: 'full-150'
        , limit: 15 //每页默认显示的数量
        , parseData: function (res) { //res 即为原始返回的数据
            var data = res.data;
            return {
                "code": status, //解析接口状态   （好像必须是0 才可以）
                "msg": data.desc, //解析提示文本
                "count": data.total, //解析数据长度
                "data": data.records //解析数据列表
            };
        }
    });

    //头工具栏事件
    table.on('toolbar(deploy)', function (obj) {
        let data = table.checkStatus(obj.config.id).data;
        switch (obj.event) {
            case 'add':
                add();
                break;
            case 'deploySelect':
                deploySelect(data);
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(deploy)', function (obj) {
        var data = obj.data;
        if (obj.event === 'update'){
            update(data);
        }else if (obj.event === 'del'){
            del(data.id)
        }else if (obj.event === 'ssh'){
            ssh(data)
        }
    });
    function ssh(data) {
        let params = {
            "ip": data.ip,
            "username": data.username,
            "password": data.password,
            "port": data.port
        };
        window["sshParams"] = params;
        const newWindow = window.open("../ssh/webssh.html");
        const loop = setInterval(function () {
            if (newWindow.closed) {
                clearInterval(loop);
            } else {
                newWindow.document.title = data.ip;
            }
        }, 1000);
    }

    function deploySelect(data) {
        if (data.length==0){
            layer.msg("请先勾选数据",{icon:2,time:3000});
            return;
        }
        var ids = "";
        for (var i = 0; i < data.length; i++) {
            ids+=data[i].id+","
        }
        ids = ids.substr(0,ids.length-1);
        $.ajax({
            type: "post",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/deploy/javaScriptDeployBatch",//url
            data:{ids:ids},
            success: function (result) {
                if (result.code == 0) {
                    layer.close(msg);
                    layer.msg(result.data,{icon:1,time:2000},function () {
                        location.reload();
                    });
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    function del(id) {
        $.ajax({
            type: "post",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/deploy/deleteDeploy",//url
            data:{id:id},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg(result.data,{icon:1,time:3000},function () {
                        location.reload();
                    });
                };
            },
            error: function () {
                alert("异常！");
            }
        });
    }

    function add() {
        layer.open({
            type: 2,
            title: '新增配置',
            area: ['1000px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["add.html", 'no'],
            success: function (layero, index) {
                form.render();
            },
            yes: function () {
            }
        });
    }
    let dropData
    function update(data) {
        layer.open({
            type: 2,
            title: '修改配置',
            area: ['1000px', '600px'],
            fix: false, //
            closeBtn: false,
            shift: 2,
            shadeClose: true,
            content: ["update.html", 'no'],
            success: function (layero, index) {
                var body = layer.getChildFrame('body', index);//获取弹出层的dom元素
                body.find("#id").val(data.id);
                body.find("#projectName").val(data.projectName);
                body.find("#projectId").val(data.projectId);
                body.find("#namespaceName").val(data.namespaceName);
                body.find("#namespaceId").val(data.namespaceId);
                body.find("#moduleName").val(data.moduleName);
                body.find("#serverId").val(data.serverId);
                body.find("#maven").val(data.maven);
                body.find("#serverName").val(data.serverName);
                body.find("#userName").val(data.userName);
                body.find("#password").val(data.password);
                body.find("#localFile").val(data.localFile);
                body.find("#remoteTargetDirectory").val(data.remoteTargetDirectory);
                body.find("#commandStart").val(data.commandStart);
                let value= data.serverId
                let selectObj=dropData.filter(item=>{
                    return item.id==value
                })
                body.find("#groupName").val(selectObj[0].ip);
                form.render();
            },
            yes: function () {
            }

        });

    }
    $(function() {
        getServer("")
        getNamespace("")
        getProject("")
        form.render('select');
    })
    function getServer(ip) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/server/getAllServer?ip="+ip,//url
            success: function (result) {
                dropData = result
                $("#serverId").html("");
                var html = "";
                $("#serverId").html("<option value=\"\">请选择服务器</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.ip + "</option>";
                    })
                }
                $("#serverId").append(html);
                form.render('select');
                if (ip != null && ip !=''){
                    $(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    $('#query').click(function(){
        search();
    });
    $(document).keyup(function(event){
        if(event.keyCode ==13){
            search();
        }
    });
    function search(){
        var content = $('#content');
        //执行重载
        table.reloadData('deploy', {
            method: 'get',
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                content: content.val()
            }
        }, 'data');
    }

    // $('.demoTable .layui-btn').on('click', function () {
    //     var type = $(this).data('type');
    //     active[type] ? active[type].call(this) : '';
    // });


    projectNameInput = function(e){
        const val = $("#projectName").val();
        getProject(val)
    }
    let projectData
    function getProject(projectName) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admProject/getAll?name="+projectName,//url
            success: function (result) {
                projectData = result
                $("#projectId").html("");
                var html = "";
                $("#projectId").html("<option value=\"\">请选择项目</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.projectName + "</option>";
                    })
                }
                $("#projectId").append(html);
                form.render('select');
                if (projectName != null && projectName !=''){
                    $(".projectId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(projectId)",function(data){
        let value=data.value
        let selectObj=projectData.filter(item=>{
            return item.id==value
        })
        $("#projectName").val(selectObj[0].projectName);
    })

    namespaceNameInput = function(e){
        const val = $("#namespaceName").val();
        getNamespace(val)
    }
    let namespaceData
    function getNamespace(name) {
        $.ajax({
            type: "GET",//方法类型
            dataType: "json",//预期服务器返回的数据类型
            url: "/admNamespace/getAll?name="+name,//url
            success: function (result) {
                namespaceData = result
                $("#namespaceId").html("");
                var html = "";
                $("#namespaceId").html("<option value=\"\">请选择命名空间</option>");
                if (result != null) {
                    $.each(result, function (index, item) {
                        html += "<option  value='" + item.id + "'>" + item.name + "</option>";
                    })
                }
                $("#namespaceId").append(html);
                form.render('select');
                if (name != null && name !=''){
                    $(".namespaceId").find(".layui-form-select").addClass("layui-form-selected")
                }
            },
            error: function () {
                alert("异常！");
            }
        });
    }
    // 监听下拉框改变事件,修改输入框中的内容
    form.on("select(namespaceId)",function(data){
        let value=data.value
        let selectObj=namespaceData.filter(item=>{
            return item.id==value
        })
        $("#namespaceName").val(selectObj[0].name);
    })
});